import React, { createRef, useCallback, useEffect, useState } from "react";
import { getUserInfo, getWords } from "../../api";
import { useNavigate } from "react-router";
import "./Words.css";
import { getUUID } from "../../utils";

const Words = () => {
    const [userInfo, setUserInfo] = useState(); //用户信息
    const [words, setWords] = useState([]); //单词卡数据
    const [currentIndex, setCurrentIndex] = useState(0); //当前卡牌索引
    const navigate = useNavigate();
    const [beEditing, setBeEditing] = useState(false); //是否在编辑中
    const fetchUser = async () => {
        //请求用户信息
        try {
            const userInfo = await getUserInfo();
            setUserInfo(userInfo);
        } catch (error) {
            console.log(error);
        }
    };
    const fetchWords = async () => {
        //请求单词卡数据
        const words = await getWords();
        setWords(words.map(item => ({ ...item, reverse: false, ref: createRef() })));
    };
    const handleLogout = () => {
        if (window.confirm("确定要退出登录吗？")) {
            localStorage.removeItem("userInfo");
            navigate("/login");
        }
    };
    const clickCard = useCallback(
        //点击卡片
        id => {
            setWords(words.map(item => (item.id === id ? { ...item, reverse: !item.reverse } : item)));
        },
        [words]
    );
    const changeWord = useCallback(
        //切换轮播图
        position => {
            if ((position === -1 && currentIndex === 0) || (position === 1 && currentIndex === words.length - 1)) return;
            setWords(words.map(item => ({ ...item, reverse: false })));
            setCurrentIndex(currentIndex + position);
        },
        [currentIndex, words]
    );
    const clickEditBtn = useCallback(
        //点击编辑按钮
        e => {
            e.stopPropagation();
            if (!words.length) return;
            if (!words[currentIndex].reverse) setWords(words.map((item, index) => (index === currentIndex ? { ...item, reverse: true } : item)));
            if (beEditing) {
                const newWords = words.map((item, index) =>
                    index === currentIndex ? { ...item, content: words[currentIndex].ref.current.value } : item
                );
                setWords(newWords);
                localStorage["words"] = JSON.stringify(newWords.map(({ id, num, content }) => ({ id, num, content })));
                setBeEditing(false);
            } else {
                setBeEditing(true);
                setTimeout(() => (words[currentIndex].ref.current.value = words[currentIndex].content));
            }
        },
        [beEditing, words, currentIndex]
    );
    const clickDeleteBtn = useCallback(() => {
        //点击删除按钮
        if (!words.length) return;
        if (window.confirm(`确定要删除${words[currentIndex].num}号卡牌吗？`)) {
            const newWords = words.filter((_, index) => index !== currentIndex);
            setWords(newWords);
            localStorage["words"] = JSON.stringify(newWords);
            if (newWords.length && newWords.length - 1 < currentIndex) {
                setCurrentIndex(newWords.length - 1);
            }
        }
    }, [words, currentIndex]);
    const clickCreateBtn = () => {
        //点击创建按钮
        const value = prompt("请输入新卡片的内容（选填）");
        if (value === null) return;
        const newWords = [...words, { id: getUUID(), num: words.length ? words[words.length - 1].num + 1 : 1, content: value, ref: createRef() }];
        setWords(newWords);
        localStorage["words"] = JSON.stringify(newWords);
    };
    useEffect(() => {
        fetchUser();
        fetchWords();
        window.addEventListener("click", () => {
            //点击空白处取消编辑内容
            setBeEditing(false);
        });
    }, []);
    return (
        <div className="wordsWrapper">
            <div className="card wordsCard">
                <div onClick={() => changeWord(-1)} className={`previous ${currentIndex <= 0 ? "disabledChangeBtn" : ""}`} />
                <div
                    onClick={() => changeWord(1)}
                    className={`next ${currentIndex === words.length - 1 || !words.length ? "disabledChangeBtn" : ""}`}
                />
                <div className="userInfoRow" onClick={handleLogout}>
                    Login: {userInfo ? userInfo.name : ""}
                </div>
                <div className="cardBox">
                    {words.length ? (
                        <div className="cardList" style={{ transform: `translateX(calc(-${currentIndex * 100}% - ${8 * currentIndex}px))` }}>
                            {words.map(word => (
                                <div
                                    key={word.id}
                                    onClick={() => clickCard(word.id)}
                                    className="wordCard"
                                    style={{ transform: word.reverse ? "rotateY(-180deg)" : "rotateY(0)" }}
                                >
                                    <div className="wordCardFront">{word.num}</div>
                                    <div className="wordCardBack" style={{ zIndex: word.reverse ? 3 : 1 }}>
                                        {beEditing ? (
                                            <input ref={word.ref} onClick={e => e.stopPropagation()} placeholder="input content" type="text" />
                                        ) : word.content ? (
                                            <>{word.content}</>
                                        ) : (
                                            <div className="emptyContentTips">内容为空，可进行编辑~</div>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div className="emptyWordTips">暂无卡牌，请手动创建~</div>
                    )}
                </div>
                {userInfo && userInfo.role === "admin" && (
                    <div className="operateBtns">
                        <div className={`button deleteButton ${words.length ? "" : "disabledButton"}`} onClick={clickDeleteBtn}>
                            删除
                        </div>
                        <div className={`button ${words.length ? "" : "disabledButton"}`} onClick={clickEditBtn}>
                            {beEditing ? "保存" : "编辑"}
                        </div>
                        <div className="button" onClick={clickCreateBtn}>
                            创建
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default Words;
